#!/bin/bash

echo ">>> 请确保以下依赖已安装: wget, unzip, curl, tar, build-essential, libgmp-dev"
echo "如果缺少，请自行使用 apt 或包管理器安装。"

# 设置安装目录为当前目录下
INSTALL_DIR="./"
mkdir -p "$INSTALL_DIR"

# 设置用户 bash 配置文件
USER_BASHRC="$HOME/.bashrc"
[ ! -f "$USER_BASHRC" ] && touch "$USER_BASHRC"

############################################
# Cryptol
############################################
echo ">>> 安装 Cryptol..."
cd "$INSTALL_DIR"
if [ ! -d "cryptol-3.3.0-ubuntu-22.04-X64" ]; then
    wget -c --show-progress https://github.com/GaloisInc/cryptol/releases/download/3.3.0/cryptol-3.3.0-ubuntu-22.04-X64.tar.gz
    tar -xzf cryptol-3.3.0-ubuntu-22.04-X64.tar.gz
    mv cryptol-3.3.0-ubuntu-22.04-X64 cryptol
    rm -f cryptol-3.3.0-ubuntu-22.04-X64.tar.gz
fi

############################################成都
# SAW
############################################
echo ">>> 安装 SAW..."
cd "$INSTALL_DIR"
if [ ! -d "saw-1.3-ubuntu-20.04-X64" ]; then
    wget -c --show-progress https://github.com/GaloisInc/saw-script/releases/download/v1.3/saw-1.3-ubuntu-20.04-X64.tar.gz
    tar -xzf saw-1.3-ubuntu-20.04-X64.tar.gz
    mv saw-1.3-ubuntu-20.04-X64 saw
    rm -f saw-1.3-ubuntu-20.04-X64.tar.gz
fi

############################################
# Z3
############################################
echo ">>> 安装 Z3..."
cd "$INSTALL_DIR"
if [ ! -d "z3-4.15.3-x64-glibc-2.39" ]; then
    wget -c --show-progress https://github.com/Z3Prover/z3/releases/download/z3-4.15.3/z3-4.15.3-x64-glibc-2.39.zip
    unzip -qo z3-4.15.3-x64-glibc-2.39.zip
    mv z3-4.15.3-x64-glibc-2.39 z3
    rm -f z3-4.15.3-x64-glibc-2.39.zip
fi

############################################
# Yices
############################################
echo ">>> 安装 Yices..."
cd "$INSTALL_DIR"
if [ ! -d "yices-2.6.4" ]; then
    wget -c --show-progress https://yices.csl.sri.com/releases/2.6.4/yices-2.6.4-x86_64-pc-linux-gnu.tar.gz
    tar -xzf yices-2.6.4-x86_64-pc-linux-gnu.tar.gz
    mv yices-2.6.4-x86_64-pc-linux-gnu yices
    rm -f yices-2.6.4-x86_64-pc-linux-gnu.tar.gz
fi

############################################
# 永久添加 PATH
############################################
echo ">>> 配置环境变量..."
grep -qxF "export PATH=$INSTALL_DIR/cryptol/bin:$INSTALL_DIR/saw/bin:$INSTALL_DIR/z3/bin:$INSTALL_DIR/yices/bin:\$PATH" "$USER_BASHRC" || \
echo "export PATH=$INSTALL_DIR/cryptol/bin:$INSTALL_DIR/saw/bin:$INSTALL_DIR/z3/bin:$INSTALL_DIR/yices/bin:\$PATH" >> "$USER_BASHRC"

echo "=============================="
echo "所有工具安装完成！"
echo "请重新打开终端或执行 'source ~/.bashrc' 以生效"
echo "=============================="
